#include "apt32f003.h"
#include "apt32f003_gpio.h"
#include "apt32f003_uart.h"
#include "system.h"
#include "hal.h"
#include "key.h"

uint32_t DebounceCount;
uint8_t LastKeyCode;
uint8_t CurrKeyCode;
uint8_t LastConfirm;

uint8_t KeyFetch(void)
{
	return (uint8_t)(((GPIOC0)->PSDR)&(0x0E)); //fetch GPIOC 0.1/0.2/0.3
}

void KeyInit(void)
{
	gpio_grp_low8bit_iocfg(GPIOC0, 0x00001110); //set GPIOC 0.1/0.2/0.3 as input
	//GPIO_PullHigh_Init(GPIOC0,1);
	//GPIO_PullHigh_Init(GPIOC0,2);
	//GPIO_PullHigh_Init(GPIOC0,3);
	GPIO_MODE_Init(GPIOC0,PUDR,0x54);
	DebounceCount = 0;
	LastKeyCode = KeyFetch();
	LastConfirm = LastKeyCode;
}
char abc[]={'t','h','a','n','k','s','!',0x0D,0x0A};char defg[]={'O','K','.',0x0D,0x0A};char temp;
void KeyTask(void)
{
	uint8_t keycode;
	
	//GPIO_Reverse(GPIOA0,IO_TEST); //test mainloop period
	if (!DebounceCount)
	{
		CurrKeyCode = KeyFetch();
		if (CurrKeyCode != LastKeyCode)
		{
			LastKeyCode = CurrKeyCode;
			DebounceCount = KEY_DEBOUNCE_CNT;
		}
	}
	else
	{
		--DebounceCount;
		if (DebounceCount)
		{
			CurrKeyCode = KeyFetch();
			if (CurrKeyCode != LastKeyCode)
			{
				LastKeyCode = CurrKeyCode;
				DebounceCount = KEY_DEBOUNCE_CNT;
			}
		}
		else
		{
			/*Key code parse*/
			keycode = LastKeyCode ^ LastConfirm;
			switch(keycode)
			{
				case SINGLE_KEY_CODE(1):
					if (SINGLE_KEY_CODE(1) & LastConfirm){
						/*key 1 press*/
						uart_send_push_nbytes(abc, sizeof(abc));
						//CSP_UART_SET_DATA(UART0,0x31);
					}else{
						/*key 1 release*/
						uart_send_push_nbytes(defg, sizeof(defg));
						//CSP_UART_SET_DATA(UART0, 0x32);
					}
				break;
				case SINGLE_KEY_CODE(2):
					if (SINGLE_KEY_CODE(2) & LastConfirm){
						/*key 2 press*/
						uart_recv_pop_byte(&temp);
						uart_send_push_nbytes(&temp, 1);
						//CSP_UART_SET_DATA(UART0, 0x33);
					}else{
						/*key 2 release*/
						uart_recv_pop_byte(&temp);
						uart_send_push_nbytes(&temp, 1);
						//CSP_UART_SET_DATA(UART0, 0x34);
					}
				break;
				case SINGLE_KEY_CODE(3):
					if (SINGLE_KEY_CODE(3) & LastConfirm){
						/*key 3 press*/
						CSP_UART_SET_DATA(UART0, 0x35);
					}else{
						/*key 3 release*/
						CSP_UART_SET_DATA(UART0, 0x36);
					}
				break;
				default:break;
			}
			
			LastConfirm = LastKeyCode;
		}
		
	}
}